package com.team1.system.stats.controller;

import com.team1.system.libraryrating.domain.LibraryRating;
import com.team1.system.libraryrating.service.ILibraryRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.text.DecimalFormat;
import java.util.*;

@Controller
public class StatsRatingController {
    @Autowired
    private ILibraryRatingService libraryRatingService;

    public Map StatsRating(){
        LibraryRating libraryRating = new LibraryRating();
        List<LibraryRating> libraryRatingList = libraryRatingService.selectLibraryRatingList(libraryRating);
        Map<Long, Double> dataMap = new HashMap<>();
        Map<Long, Double> numMap = new HashMap<>();

        //将不同ID和对应的书的评价等级总和放入map键值对
        for(LibraryRating l:libraryRatingList){
            long  bookId = l.getBookId();
            double rating = l.getRating();
            if (dataMap.containsKey(bookId)) {
                dataMap.put(bookId,dataMap.get(bookId) +  rating);
                numMap.put(bookId,numMap.get(bookId) +  1);
                //num[Math.toIntExact(bookId)]++;

            } else {
                dataMap.put(bookId,rating);
                numMap.put(bookId, 1.0);
            }
        }

        Map<Long, Double> ratingMap = new HashMap<>();
        Set<Long> set = dataMap.keySet();
        DecimalFormat df = new DecimalFormat("#0.0");
        for (Long bookId : set) {
            double rating = dataMap.get(bookId);
            double num = numMap.get(bookId);
            double avgRating = (double)rating/num;
            ratingMap.put(bookId, Double.valueOf(df.format(avgRating)));
        }

        return ratingMap;
    }

    public double RatingById(Long bookId){
        Map<Long, Double> ratingMap = StatsRating();
        double rating = ratingMap.get(bookId);

        return rating;
    }

    public double[][] RatingTop(){
        LibraryRating libraryRating = new LibraryRating();
        List<LibraryRating> libraryRatingList = libraryRatingService.selectLibraryRatingTop(libraryRating);
        double [][]top = new double[10][2];
        //Map<Long, Double> topMap = new HashMap<>();
        DecimalFormat df = new DecimalFormat("#0.0");
        int i=0;
        for(LibraryRating l:libraryRatingList){
            Long bookId = l.getBookId();
            double avgRating = l.getRating();
            top[i][0] = bookId;
            top[i][1] = Double.valueOf(df.format(avgRating));
            i++;
        }
        return top;
    }
}
